package com.hcloud.auth.api.token;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hcloud.auth.api.user.HcloudUserDetails;
import com.hcloud.common.core.constants.AuthConstants;
import com.hcloud.system.core.bean.user.User;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 解析jwt并将信息放入Authentication
 *
 * @Auther hepangui
 * @Date 2018/11/14
 */
public class AdditionalUserAuthenticationConverter extends DefaultUserAuthenticationConverter {

    @Override
    public Authentication extractAuthentication(Map<String, ?> map) {
        if (map.containsKey(AuthConstants.USER)) {
            var object = map.get(AuthConstants.USER);
            User user = null;
            if (object != null) {
                user = JSONObject.parseObject(JSONObject.toJSONString(object), User.class);
            }
            var myUserDetail = new HcloudUserDetails(user);
            Set<SimpleGrantedAuthority> authoritySet = new HashSet();
            Object o = map.get(AuthConstants.AUTHORITY);
            if (o != null) {
                List<String> strings = JSONArray.parseArray(JSONArray.toJSONString(map.get(AuthConstants.AUTHORITY)), String.class);
                authoritySet = strings.stream().map(s -> new SimpleGrantedAuthority(s)).collect(Collectors.toSet());
            }
            return new UsernamePasswordAuthenticationToken(myUserDetail, "N/A", authoritySet);
        }
        return null;
    }


}
